package com.example.sonny.dutest;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.cengalabs.flatui.FlatUI;
import com.example.sonny.Constraint;
import com.example.sonny.dutest.interfaces.BaseActivityI;
import com.example.sonny.util.AsyncHttpClientUtil;
import com.example.sonny.util.VolleyImageUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class PublishBookActivity extends BaseActivity implements BaseActivityI{


    private static final int REQUEST_IMAGE = 1024;
    private Button btn_back;
    private Button btn_done;
    private EditText et_name;
    private EditText et_intro;
    private ImageView iv_book;

    private Bitmap bitmap;


    private String name;
    private String intro;

    private String action;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_book);

        preInit();
        initView();
        initListener();

    }

    @Override
    public void preInit() {

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setBackgroundDrawable(FlatUI.getActionBarDrawable(this, FlatUI.GRASS, false));
    }

    public void initView() {
        et_name = (EditText)findViewById(R.id.et_book_name);
        et_intro = (EditText)findViewById(R.id.et_intr);
        btn_back = (Button)findViewById(R.id.btn_publish_back);
        btn_done  = (Button)findViewById(R.id.btn_publish_done);
        iv_book = (ImageView)findViewById(R.id.setting_book_avater_img);
        iv_book.setClickable(true);
    }

    @Override
    public void initData() {

    }

    public void initListener() {
        btn_back.setOnClickListener(this);
        btn_done.setOnClickListener(this);
        iv_book.setOnClickListener(this);
    }

    private boolean getData() {
        name  = et_name.getText().toString();
        intro = et_intro.getText().toString();
        if(name.equalsIgnoreCase("")){
            toast("书名不能为空");
            return false;
        }
        if(intro.equalsIgnoreCase("")){
            toast("介绍不能为空");
            return false;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_publish_book, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if(id == android.R.id.home) {
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        }

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_publish_back:
                 finish();
                break;
            case R.id.btn_publish_done:
                if(getData()){
                    try {
                        publishBookJob();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.setting_book_avater_img:
                selectJob();
        }

    }

    private void selectJob() {
        Intent intent = new Intent(getApplicationContext(), MultiImageSelectorActivity.class);

// 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);

// 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);

// 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // 获取返回的图片列表
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                // 处理你自己的逻辑 ....
                iv_book.setImageURI(Uri.parse(path.get(0)));
                //Do some compress work
                bitmap = VolleyImageUtils.getScaledBitmap(path.get(0),256,256);
                 //VolleyImageUtils.compress(path.get(0),path.get(0),48,48,50);
            }
        }
    }

    private void publishBookJob() throws FileNotFoundException {
        //TODO get specific data structure for posting api



        AsyncHttpClient client  = AsyncHttpClientUtil.getInstence();
        action = "api/books";//TODO set api URL
        String imgUrl = Constraint.encodeTobase64(bitmap);
        RequestParams requestParams = new RequestParams();
        requestParams.add("email",token);
        requestParams.add("name",name);
        requestParams.add("intro",intro);
        requestParams.add("imgUrl", imgUrl);
        Log.i(LogTag,imgUrl);
        client.post(Constraint.API_URL+action,requestParams,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                toast("发布成功");
                finish();
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                toast("发布失败");
            }
        });


    }
}
